package org.hubwork.base.common;

import java.lang.reflect.Method;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springside.modules.test.spring.SpringContextHolder;

public class DataSourceContextInterceptor implements MethodInterceptor{

  private ServerIdFinder finder = null;

  public Object invoke (MethodInvocation invocation) throws Throwable{
    if (this.finder == null){
      this.finder = HubApplicationContext.get(DefaultServerIdFinder.class);
    }
    Object out = null;
    Method m = invocation.getMethod ();
    Routable r = m.getAnnotation (Routable.class);
    if (r == null){
      r = m.getDeclaringClass ().getAnnotation (Routable.class);
    }
    if (r != null){    	
        String dsName[] = r.value();
        if(dsName.length > 0){
        	String tmpName = dsName[0];
        	ContextSupport.setCurrentDataSource (tmpName);
        }
    }
    out = invocation.proceed ();
    return out;
  }
}
